var areasInfo = require('../../utils/area.js');
var areaSearch = require('../../utils/areaInfo.js');
var uuid;
//商家状态
var STATUS_ON_LIST = "STATUS_ON_LIST";
var STATUS_ON_CHECK = "STATUS_ON_CHECK";
var STATUS_PASS = "STATUS_PASS";
var STATUS_BACK = "STATUS_BACK";
var STATUS_ON_CHECK_AGAIN = "STATUS_ON_CHECK_AGAIN";

const app = getApp();
var url = app.data.url;
var picRoot = app.data.picRoot;
import Dialog from "@vant/weapp/dialog/dialog";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    picker:{},
    showView: false,
    btnShow: true,
    isPicActive : false,
    isPicDeletable : true,
    activeShow: false,
    areaInputShow: false,
    examineStatus: '',
    active: 'N',
    citySelectShow: false,
    typeOptionShow: false,
    merchant: {},
    displayArea: '',
    displayType: '',
    currentArea: '',
    overLayShow: false,
    areaList: [],
    items: [

    ],
    examineTimes: 0,
    typeColumns: ['餐饮', '酒店', '景点', '车服', '加油', '特产', '超市','医疗保健', '娱乐', '美容美发', '名牌服饰'],
    areaColumns: [
      "无"
    ],//areaColumns只使用一次，初始化时候使用一次，之后每次刷新数据需要一个新对象，控件问题
    //fileList: [{ url:"http://111.229.48.117/zdtPic/merchant/cover/iXvTRq3YCLmXNHxlCqeg.png"}],
    coverFileList: [],
    envFileList: [],
    openFileList: [],
    fileSavePath: '',
    //商家字段显示
    name: '',
    phone: '',
    province: '',
    city: '',
    area: '',
    address: '',
    longitude: '',
    latitude: '',
    type: '',
    description: '',
    isCheckActive: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    /**const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true
    innerAudioContext.src = '/audio/test.mp3'
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })**/
    var th = this;
    var isCheckActive = options.isCheckActive;

    /*wx.getStorage({
      key: "uuid",
      success(res) {
        uuid = res.data
        //查询商家信息
        th.queryMerchant(uuid);
      }
    })*/

    //省市区选择赋值
    th.setData({
      areaList: areasInfo,
      isCheckActive: isCheckActive
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var th = this;
    th.data.picker = th.selectComponent('#picker');
    //以下有用到picker,所以将查询放在下面
    wx.getStorage({
      key: "uuid",
      success(res) {
        uuid = res.data
        //查询商家信息
        th.queryMerchant(uuid);
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  openTypeOption: function() {
    var th = this;
    if(th.data.examineTimes > 0){
      //审核通过一次,不可以更改入驻类型
      wx.showToast({
        title: "入驻类型一经审核通过,不允许修改!",
        icon: "none",
        duration: 3000
      })
    } else {
      th.setData({
        typeOptionShow: true
      });
    }
    
  },


  //打开省市区弹出框
  openCitySelect: function() {
    var th = this;
    th.setData({
      citySelectShow: true
    });

  },

  //打开域弹出框
  openAreaSelect: function () {
    var th = this;
    th.setData({
      areaOptionShow: true
    });

  },

  //点击确认选中并且关闭省市区弹出框
  citySelectConfirm: function(res) {
    var th = this;
    if (th.data.area != res.detail.values[2].code){
       //有修改
      th.setData({
        areaInfo : ""
      })
    }
    th.setData({
      citySelectShow: false,
      displayArea: res.detail.values[0].name + '->' + res.detail.values[1].name + '->' + res.detail.values[2].name,
      province: res.detail.values[0].code,
      city: res.detail.values[1].code,
      area: res.detail.values[2].code
    });
    //显示详细区域选择
    th.pickUpAreaInfo(res.detail.values[0].code, res.detail.values[1].code, res.detail.values[2].code);
  },

  //点击取消关闭省市区弹出框
  citySelectCancel: function() {
    var th = this;
    th.setData({
      citySelectShow: false
    });
  },

  typeOptionConfirm: function(event) {
    var th = this;
    th.setData({
      typeOptionShow: false,
      displayType: event.detail.value,
      type: event.detail.index
    });
    
  },

  areaOptionConfirm: function (event) {
    var th = this;
    th.setData({
      areaOptionShow: false,
      areaInfo: event.detail.value
      //type: event.detail.index
    });
  },

  typeOptionCancel: function() {
    var th = this;
    th.setData({
      typeOptionShow: false
    });
  },

  areaOptionCancel: function () {
    var th = this;
    th.setData({
      areaOptionShow: false
    });
  },

  //点击遮罩层关闭省市区弹出框
  onCloseCitySelect: function() {
    var th = this;
    th.setData({
      citySelectShow: false
    });
  },

  onCloseAreaSelect: function () {
    var th = this;
    th.setData({
      areaOptionShow: false
    });
  },

  afterReadCover(event) {
    var th = this;
    th.afterRead(event, "cover");
  },

  afterReadEnv(event) {
    var th = this;
    th.afterRead(event, "env");
  },

  afterReadOpen(event) {
    var th = this;
    th.afterRead(event, "open");
  },

  /**
   * 上传图片
   */
  afterRead(event, flag) {
    let _that = this;
    const {
      file
    } = event.detail;
    // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
    _that.onOverLayShow();
    for (var i = 0; i < file.length; i++) {
      wx.uploadFile({
        url: url + '/MerchantApi/uploadPic?flag=' + flag + "&uuid=" + uuid,
        filePath: file[i].path,
        header: {
          "Content-Type": "multipart/form-data"
        },
        name: 'file',
        success(res) {
          if (res.statusCode == 200) {
            // 上传成功
            if (flag == "cover") {
              const {
                coverFileList = []
              } = _that.data;
              coverFileList.push({
                ...file,
                url: picRoot + res.data
              });
              _that.setData({
                coverFileList
              });
              if (i == (file.length)) {
                _that.onOverLayHide();
              }
            } else if (flag == "env") {
              const {
                envFileList = []
              } = _that.data;
              envFileList.push({
                ...file,
                url: picRoot + res.data
              });
              _that.setData({
                envFileList
              });
              if (i == (file.length)) {
                _that.onOverLayHide();
              }
              console.log(envFileList);
            } else {
              const {
                openFileList = []
              } = _that.data;
              openFileList.push({
                ...file,
                url: picRoot + res.data
              });
              _that.setData({
                openFileList
              });
              if (i == (file.length)) {
                _that.onOverLayHide();
              }
            }
          } else {
            wx.showToast({
              title: "上传失败!",
              icon: "none",
              duration: 2000
            })
          }
        }
      });
    }
  },

  deleteCoverImg: function(option) {
    var th = this;
    let {
      coverFileList = []
    } = th.data;

    var str = coverFileList[option.detail.index].url;
    var split = str.split(picRoot);

    //发起请求,删除图片(提醒确认)
    Dialog.confirm({
      title: '是否删除',
      message: '删除了将无法恢复哦'
    }).then(() => {
      // on confirm
      th.onOverLayShow();
      wx.request({
        url: url + '/MerchantApi/delPic?flag=cover&path=' + split[1] + "&uuid=" + uuid,
        data: {},
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.code == 200) {
            th.onOverLayHide();
            coverFileList.splice(option.detail.index, 1);
            th.setData({
              coverFileList: coverFileList
            });
            wx.showToast({
              title: "操作成功!",
              icon: "success",
              duration: 3000
            })
          } else {
            th.onOverLayHide();
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
            })
          }
        },
        fail: function(res) {
          th.onOverLayHide();
          console.info('submit fail');
        },
        complete: function(res) {
          console.info('submit complete');
        }
      })

    }).catch(() => {
      // on cancel
    });


  },

  deleteEnvImg: function(option) {
    var th = this;
    let {
      envFileList = []
    } = th.data;

    var str = envFileList[option.detail.index].url;
    var split = str.split(picRoot);

    //发起请求,删除图片(提醒确认)
    Dialog.confirm({
      title: '是否删除',
      message: '删除了将无法恢复哦'
    }).then(() => {
      // on confirm
      th.onOverLayShow();
      wx.request({
        url: url + '/MerchantApi/delPic?flag=env&path=' + split[1] + "&uuid=" + uuid,
        data: {},
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.code == 200) {
            th.onOverLayHide();
            envFileList.splice(option.detail.index, 1);
            th.setData({
              envFileList: envFileList
            });
            wx.showToast({
              title: "操作成功!",
              icon: "success",
              duration: 3000
            })
          } else {
            th.onOverLayHide();
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
            })
          }
        },
        fail: function(res) {
          th.onOverLayHide();
          console.info('submit fail');
        },
        complete: function(res) {
          console.info('submit complete');
        }
      })

    }).catch(() => {
      // on cancel
    });
  },

  deleteOpenImg: function(option) {
    var th = this;
    let {
      openFileList = []
    } = th.data;

    var str = openFileList[option.detail.index].url;
    var split = str.split(picRoot);

    //发起请求,删除图片(提醒确认)
    Dialog.confirm({
      title: '是否删除',
      message: '删除了将无法恢复哦'
    }).then(() => {
      // on confirm
      th.onOverLayShow();
      wx.request({
        url: url + '/MerchantApi/delPic?flag=open&path=' + split[1] + "&uuid=" + uuid,
        data: {},
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data.code == 200) {
            th.onOverLayHide();
            openFileList.splice(option.detail.index, 1);
            th.setData({
              openFileList: openFileList
            });
            wx.showToast({
              title: "操作成功!",
              icon: "success",
              duration: 3000
            })
          } else {
            th.onOverLayHide();
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
            })
          }
        },
        fail: function(res) {
          th.onOverLayHide();
          console.info('submit fail');
        },
        complete: function(res) {
          console.info('submit complete');
        }
      })

    }).catch(() => {
      // on cancel
    });
  },



  /**弹框 */
  onOverLayShow() {
    this.setData({
      overLayShow: true
    });
  },

  onOverLayHide() {
    this.setData({
      overLayShow: false
    });
  },

  onNameChange(event) {
    let _that = this;
    _that.setData({
      name: event.detail
    });
  },

  onPhoneChange(event) {
    let _that = this;
    _that.setData({
      phone: event.detail
    });
  },

  onDescriptionChange(event) {
    let _that = this;
    _that.setData({
      description: event.detail
    });
  },

  onAddressChange(event) {
    let _that = this;
    _that.setData({
      address: event.detail
    });
  },

  examine() {
    var th = this;
    th.updateMerchant("examine");
  },

  save() {
    var th = this;
    th.updateMerchant("update");
  },

  updateMerchant(flag) {
    let _that = this;
    let name = _that.data.name;
    let phone = _that.data.phone;
    let province = _that.data.province;
    let city = _that.data.city;
    let area = _that.data.area;
    let address = _that.data.address;
    let longitude = _that.data.longitude;
    let latitude = _that.data.latitude;
    let type = _that.data.type;
    //let active = _that.data.active;
    let description = _that.data.description;
    let areaInfo = _that.data.areaInfo;
    console.log("--------------" + type);
    console.log("--------------" + areaInfo);
    //校验
    var msg = "";
    if (!name) {
      msg = "请输入商家名称";
    } else if (!phone) {
      msg = "请输入联系电话"
    } else if (!area) {
      msg = "请选择省市区信息"
    } else if (!address) {
      msg = "请输入详细地址"
    } else if (!longitude) {
      msg = "请点击顶部-调整定位-功能进行定位,方便用户前往您的店铺哦"
    } else if(type == -1){
      msg = "请选择入驻类型"
    }

    if (msg != "") {
      Dialog.alert({
        title: '注意',
        message: msg
      }).then(() => {
        // on close
      });
      return false;
    }

    //详细区域信息
    var areaMsg = "";
    if (areaInfo){
      for(var i = 0; i < _that.data.items.length; i++){
        if (_that.data.items[i].text == areaInfo){
              areaMsg = _that.data.items[i].id;
              break;
        }
      }
    }

    console.log("--------------选择域 : " + areaMsg);

    var tempData = {
      name: name,
      phone: phone,
      province: province,
      city: city,
      district: area,
      address: address,
      longitude: longitude,
      latitude: latitude,
      uuid: uuid,
      type: type,
      //active: active ? "Y" : "N",
      description: description,
      town: areaMsg
    }

    console.info(tempData);

    if (flag == "examine") {
      Dialog.confirm({
        title: '是否确认提交审核',
        message: '请仔细检查您的信息,一旦提交审核后,审核期间将无法对其做任何的修改哦!'
      }).then(() => {
        // on confirm
        _that.updateMerchantByUuid(tempData, flag);
      }).catch(() => {
        // on cancel
        return false;
      });
    } else {
      _that.updateMerchantByUuid(tempData, flag);
    }

  },

  updateMerchantByUuid(tempData, flag) {
    var _that = this;
    wx.request({
      url: url + '/MerchantApi/updateMerchantByUuid?flag=' + flag,
      data: tempData,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res);
        if (res.data.code == 200) {
          if (flag == "examine") {
            _that.setData({
              examineStatus: "审核中",
              btnShow: false,
              isPicActive:true,
              isPicDeletable:false
            })
          }
          wx.showToast({
            title: "操作成功!",
            icon: "success",
            duration: 3000
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 3000
          })
        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })
  },

  /**onActiveChange: function({
    detail
  }) {
    let _that = this;
    let isCheckActive = _that.data.isCheckActive;
    if (!isCheckActive) {
      Dialog.alert({
        message: ' 您已过了免费试用期或使用有效期,请前往充值'
      }).then(() => {
        // on close
      });
    } else {
      this.setData({
        active: detail
      });
    }
  },*/

  activeTip() {
    let _that = this;
    let isCheckActive = _that.data.isCheckActive;
    if (!isCheckActive) {
      Dialog.alert({
        message: ' 您已过了免费试用期或使用有效期,请前往充值'
      }).then(() => {
        // on close
      });
    }

  },

  mapViewTap() {
    var th = this;
    var longitude = th.data.longitude;
    var latitude = th.data.latitude;
    if (longitude != '') {
      wx.openLocation({
        latitude: Number(latitude),
        longitude: Number(longitude),
        scale: 17
      })
    } else {

      wx.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function(res) {
          console.log(res)
          wx.openLocation({
            latitude: res.latitude,
            longitude: res.longitude,
            scale: 17
          })
        }
      })

    }

  },

  mapView: function() {
    var th = this;
    wx.chooseLocation({
      success: function(res) {
        var s1 = res.longitude + "";
        var s2 = res.latitude + "";
        var str1 = s1.substring(0, s1.indexOf(".") + 7);
        var str2 = s2.substring(0, s2.indexOf(".") + 7);
        th.setData({
          longitude: str1,
          latitude: str2,
          address: res.address
        })

      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },


  //查询商家信息
  queryMerchant(uuid) {
    var th = this;
    wx.request({
      url: url + '/MerchantApi/queryMerchantByUuid',
      data: {
        uuid: uuid
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.info(res.data);
        if (res.data.code == 200) {
          //回显状态
          var status = "";
          console.log("------------审核通过次数 : " + res.data.data.examineTimes + " --------------------");
          if (res.data.data.examineStatus == STATUS_ON_LIST) {
            status = "编制中";
          } else if (res.data.data.examineStatus == STATUS_ON_CHECK) {
            status = "审核中";
            th.setData({
              btnShow: false,
              isPicActive: true,
              isPicDeletable: false
            })
          } else if (res.data.data.examineStatus == STATUS_PASS) {
            status = "审核通过";
            //显示是否上架选项
            th.setData({
              activeShow: true
            })
          } else if (res.data.data.examineStatus == STATUS_BACK) {
            status = "审核不通过";
            Dialog.alert({
              message: '您的信息审核不通过哦 : ' + res.data.data.examineReason
            }).then(() => {
              // on close
            });
          }
          //回显商家封面图片
          var coverPic = [];
          var cover = new Object();
          if (res.data.data.coverIcon != "" && res.data.data.coverIcon != null) {
            cover.url = picRoot + res.data.data.coverIcon;
            coverPic[0] = cover;
          }
          //回显商家环境图片
          var envPic = [];
          if (res.data.data.envIcon != "" && res.data.data.envIcon != null) {
            if (res.data.data.envIcon.indexOf(",") != -1) {
              var envArr = res.data.data.envIcon.split(",");
              for (var i = 0; i < envArr.length; i++) {
                var env = new Object();
                env.url = picRoot + envArr[i];
                envPic[i] = env;
              }
            } else {
              var env = new Object();
              env.url = picRoot + res.data.data.envIcon;
              envPic[0] = env;
            }
          }

          var openPic = [];
          if (res.data.data.openIcon != "" && res.data.data.openIcon != null) {
            if (res.data.data.openIcon.indexOf(",") != -1) {
              var openArr = res.data.data.openIcon.split(",");
              for (var i = 0; i < openArr.length; i++) {
                var open = new Object();
                open.url = picRoot + openArr[i];
                openPic[i] = open;
              }
            } else {
              var open = new Object();
              open.url = picRoot + res.data.data.openIcon;
              openPic[0] = open;
            }
          }
          console.log(res.data.data.displayType);
          th.setData({
            examineTimes: res.data.data.examineTimes,
            name: res.data.data.name,
            phone: res.data.data.phone,
            province: res.data.data.province,
            city: res.data.data.city,
            area: res.data.data.district,
            address: res.data.data.address,
            description: res.data.data.description,
            longitude: res.data.data.longitude,
            latitude: res.data.data.latitude,
            displayArea: res.data.data.displayArea,
            type: res.data.data.type,
            active: res.data.data.active == "Y" ? true : false,
            displayType: res.data.data.displayType,
            currentArea: res.data.data.district,
            examineStatus: status,
            coverFileList: coverPic,
            envFileList: envPic,
            openFileList: openPic
          })

          if (res.data.data.displayArea){
            //已经有省市区信息
             th.setData({
               areaInputShow : true
             })
            console.info("-----------------省：" + res.data.data.province);
            console.info("-----------------市：" + res.data.data.city);
            console.info("-----------------区：" + res.data.data.district);
            //根据获取的当前区/县,继续获取镇与商区信息
            th.pickUpAreaInfo(res.data.data.province, res.data.data.city, res.data.data.district, res.data.data.town); 
             
          }

        }
      },
      fail: function(res) {
        console.info('submit fail');
      },
      complete: function(res) {
        console.info('submit complete');
      }
    })
  },

  pickUpAreaInfo(province,city,district,displayCode){
    var th = this;
    var temp = new Array();
    //根据获取的当前区/县,继续获取镇与商区信息
    var areaData = areaSearch.data;
    outer:
    for (var i = 0; i < areaData.all.length; i++) {
      //循环省
      if (areaData.all[i].id == province) {
        console.info("匹配省:" + areaData.all[i].id);
        var citys = areaData.all[i].children;
        for (var k = 0; k < citys.length; k++) {
          //循环市
          if (citys[k].id == city) {
            console.info("匹配市:" + citys[k].id);
            var areas = citys[k].children;
            for (var g = 0; g < areas.length; g++) {
              if (areas[g].id == district) {
                console.info("匹配区:" + areas[g].id);
                th.setData({
                  items: areas[g].children
                })
                break outer;
              }
            }

          }
        }
      }

    }
    console.info("****************" + JSON.stringify(th.data.items));
    //获取镇与商区信息后填充数组对象
    for (var i = 0; i < th.data.items.length; i++) {
      temp[i] = th.data.items[i].text;
      if (displayCode == th.data.items[i].id){
          th.setData({
            areaInfo: th.data.items[i].text
          })
      }
    }
    console.info("****************" + JSON.stringify(temp));
    //填充完后刷新picker控件
    console.info(th.data.picker);
    th.data.picker.setColumnValues(0, temp); 

  }



})